#include "frozen-bubble.h"

FBLevel *level_new ()
{
	FBLevel *level;
	
	if (!(level = malloc (sizeof (FBLevel))))
	{
		fprintf (logfile, "level: Unable to malloc FBLevel\n");
		exit (EXIT_FAILURE);
		return NULL;
	}
	
	memset (level->balls, -1, sizeof (int) * LEVEL_ROWS * LEVEL_COLS);
	level->next = NULL;
	
	return level;
}

void level_free (FBLevel *level)
{
	free (level);
}

FBLevelSet *level_set_new (const char *file)
{
	FBLevelSet *set;
	FBLevel *level = NULL, **lastnext;
	FILE *fptr;
	char filename[50] = { 0 };
	char line[100];
	char *lineptr = line;
	int row = 0, col = 0, levels = 0;
	char ball;
	
	if (!(set = malloc (sizeof (FBLevelSet))))
	{
		fprintf (logfile, "level: Unable to malloc FBLevelSet\n");
		exit (EXIT_FAILURE);
		return NULL;
	}
	
	strcat (filename, FPATH);
	strcat (filename, "data/");
	strcat (filename, file);
	
	if (!(fptr = fopen (filename, "r")))
	{
		fprintf (logfile, "level: Unable to open levelset file '%s'\n", file);
		exit (EXIT_FAILURE);
		return NULL;
	}
	
	lastnext = &set->levels;
	
	while (fgets (line, 100, fptr))
	{
		lineptr = line;
		
		if (!level)
			level = level_new ();
		
		if (*lineptr == ' ')
			while (*(++lineptr) == ' ' && *lineptr != 0);
		
		while (sscanf (lineptr, "%c", &ball) == 1)
		{
			switch (ball)
			{
			case 0:
			case 10:
			case 13:
				break;
			
			case '-':
				level->balls[row][col++] = -1;
				break;
			
			default:
				level->balls[row][col++] = ball - '0';
				break;
			}
			
			while (*(++lineptr) == ' ' && *lineptr != 0);
		}
		
		if (col == 0)
			continue;
		
		if (col != LEVEL_COLS - (row % 2))
		{
			fprintf (logfile, "level: Unexpected number of columns %d on level %d row %d\n",
			                  col, levels, row);
			
			exit (EXIT_FAILURE);
			return NULL;
		}
		
		col = 0;
		
		if (++row == LEVEL_ROWS)
		{
			row = 0;
			
			/*fprintf (logfile, "level: Level %d\n\t", levels + 1);
			
			for (int row = 0; row < LEVEL_ROWS; row++)
			{
				if (row % 2)
					fprintf (logfile, " ");
				
				for (int col = 0; col < LEVEL_COLS - (row % 2); col++)
				{
					int ball = level->balls[row][col];
					
					if (ball < 0)
						fprintf (logfile, " - ");
					else
						fprintf (logfile, "%2d ", ball);
				}
				
				fprintf (logfile, "\n\t");
			}
			
			fprintf (logfile, "\n");*/
			
			*lastnext = level;
			lastnext = &level->next;
			level = NULL;
			
			levels++;
		}
	}
	
	if (level)
		level_free (level);
	
	fprintf (logfile, "level: Loaded %d levels\n", levels);
	
	fclose (fptr);
	return set;
}

void _level_set_free_level (FBLevel *level)
{
	if (level->next)
		_level_set_free_level (level->next);
	
	level_free (level);
}

void level_set_free (FBLevelSet *set)
{
	_level_set_free_level (set->levels);
	
	free (set);
}

